import dayjs from "dayjs";
import { message } from "@/utils/message";
import { ElMessageBox, Sort } from "element-plus";
import { reactive, ref, onMounted, toRaw, computed } from "vue";
import { useUserStoreHook } from "@/store/modules/user";
import { CommonUtils } from "@/utils/common";
import { PaginationProps } from "@pureadmin/table";
import {
  InspectionCheckQuery,
  getInspectionCheckListApi,
  exportInspectionCheckApi,
  deleteInspectionCheckApi
} from "@/api/airport/inspection/inspectionCheck";
import {DeptTreeDTO, getDeptTree} from "@/api/system/dept";

// 正式开始js代码，也就是页面初始化时会执行的代码
export function useInspectionCheckHook() {
  // 设置默认的排序规则，按检查开始时间从近到远排序
  const defaultSort: Sort = {
    prop: "startTime",
    order: "descending"
  };
  // 分页设置
  const pagination: PaginationProps = {
    total: 0,
    pageSize: 20,
    currentPage: 1,
    background: true
  };

  // 定义初始搜索参数
  const initialSearchFormParams = {
    checkTermCode: "",
    inspectionResult: "",
    deptId: undefined,
    startTime: undefined,
    endTime: undefined,
    determinationStandard: "",
    inspectionUserName: ""
  };

  // 创建一个响应式的对象，用于存储查询参数
  const searchFormParams = reactive<InspectionCheckQuery>({...initialSearchFormParams});
  // 定义检查结果对应的颜色映射
  const inspectionResultColorMap = {
    '1': 'success',
    '2': 'danger',
    '3': 'info'
  };

  // 定义处理方式的映射关系
  const dealTypeMap = {
    '0': '检查通过',
    '1': '直接整改',
    '2': '建模后整改'
  };

  // 定义处理方式对应的颜色映射
  const dealTypeColorMap = {
    '0': 'success',
    '1': 'warning',
    '2': 'danger'
  };

  // 注意：这个函数是一个计算属性，也就是说当用户设置时间选择框的属性时，这个函数会自动执行，并且会将时间选择框的属性赋值给searchFormParams的beginTime和endTime
  const timeRange = computed<[string, string] | null>({
    get() {
      if (searchFormParams.startTime && searchFormParams.endTime) {
        return [searchFormParams.startTime, searchFormParams.endTime];
      } else {
        return null;
      }
    },
    set(v) {
      if (v?.length === 2) {
        searchFormParams.startTime = v[0];
        searchFormParams.endTime = v[1];
      } else {
        searchFormParams.startTime = undefined;
        searchFormParams.endTime = undefined;
      }
    }
  });

  const deptTree = ref<DeptTreeDTO[]>([]);

  // 获取部门树
  const fetchDeptTree = async () => {
    try {
      const { data } = await getDeptTree();
      if (data) {
        // 转换数据格式
        const convertDeptTree = (nodes) => {
          return nodes.map(node => ({
            value: node.id,
            label: node.label,
            children: node.children ? convertDeptTree(node.children) : undefined
          }));
        };
        // 若 data 本身是数组，直接转换
        if (Array.isArray(data)) {
          deptTree.value = convertDeptTree(data);
        } else {
          // 若 data 不是数组，将其包裹成数组再转换
          deptTree.value = convertDeptTree([data]);
        }
      }
    } catch (error) {
      console.error('获取部门树数据失败:', error);
    }
  };

  // 检查结果选项
  const inspectionResultOptions = [
    { label: '检查通过', value: '1' },
    { label: '不通过', value: '2' },
    { label: '不适用', value: '3' }
  ];

  // 表格数据
  const dataList = ref([]);
  // 标志：保存表格是否正在加载数据
  const pageLoading = ref(true);
  // 标志：保存表格是否有选中数据（用于存储用户在表格中选中的多条记录）
  const multipleSelection = ref([]);
  // 标志：保存表格的排序规则，在上面被初始化了
  const sortState = ref<Sort>(defaultSort);
  // 表格列配置
  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left"
    },
    {
      label: "检查计划名称",
      prop: "inspectionName",
      minWidth: 200
    },
    {
      label: "检查人",
      prop: "inspectionUserName",
      minWidth: 60
    },
    {
      label: "检查结果",
      prop: "inspectionResult",
      minWidth: 90,
      cellRenderer: ({ row, props }) => {
        const result = row.inspectionResult;
        let resultText = '';
        let resultColor = 'info'; // 默认颜色

        if (result === "1") {
          resultText = "检查通过";
          resultColor = inspectionResultColorMap['1'];
        } else if (result === "2") {
          resultText = "不通过";
          resultColor = inspectionResultColorMap['2'];
        } else if (result === "3") {
          resultText = "不适用";
          resultColor = inspectionResultColorMap['3'];
        } else {
          resultText = result;
        }

        return (
          <el-tag
            size="large"
            type={resultColor}
            effect="plain"
          >
            {resultText}
          </el-tag>
        );
      }
    },
    // 添加处理方式列
    {
      label: "处理方式",
      prop: "dealType",
      minWidth: 100,
      cellRenderer: ({ row, props }) => {
        const dealType = row.dealType?.toString(); // 确保是字符串类型
        const dealTypeText = dealTypeMap[dealType] || dealType || '';
        const dealTypeColor = dealTypeColorMap[dealType] || 'info'; // 默认颜色

        return (
          <el-tag
            size="large"
            type={dealTypeColor}
            effect="plain"
          >
            {dealTypeText}
          </el-tag>
        );
      }
    },
    // 修改检查对象列，展示 professional 字段
    {
      label: "检查主题",
      prop: "professional",
      minWidth: 90
    },
    {
      label: "检查部门",
      prop: "checkDeptName",
      minWidth: 90
    },
    {
      label: "检查对象",
      prop: "inspectedDeptName",
      minWidth: 90
    },
    {
      label: "判定标准",
      prop: "determinationStandard",
      minWidth: 250
    },
    {
      label: "检查时间",
      minWidth: 160,
      prop: "startTime",
      sortable: "custom",
      formatter: ({ startTime }) =>
        dayjs(startTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];
  // 表格列的排序变化的时候，会触发这个函数
  function onSortChanged(sort: Sort) {
    sortState.value = sort;
    // 表格列的排序变化的时候，需要重置分页
    pagination.currentPage = 1;
    // 表格列的排序变化的时候，需要重新查询数据
    getInspectionCheckList();
  }
  // 表格的搜索按钮点击的时候，会触发这个函数
  async function onSearch(tableRef) {
    // 点击搜索的时候，需要重置排序，按检查开始时间从近到远排序
    sortState.value = defaultSort;
    tableRef.getTableRef().sort(defaultSort.prop, defaultSort.order);
    // 重置分页
    pagination.currentPage = 1;
    getInspectionCheckList();
  }
  //  重置表单
  function resetForm(formEl, tableRef) {
    if (!formEl) return;
    // 清空查询参数到初始状态
    Object.assign(searchFormParams, initialSearchFormParams);
    // 清空时间查询
    searchFormParams.startTime = undefined;
    searchFormParams.endTime = undefined;
    // 重置排序，按检查开始时间从近到远排序
    sortState.value = defaultSort;
    tableRef.getTableRef().sort(defaultSort.prop, defaultSort.order);
    // 重置分页
    pagination.currentPage = 1;
    // 重新查询数据
    getInspectionCheckList();
  }
  //  获取检查项列表（查询数据）
  async function getInspectionCheckList() {
    pageLoading.value = true;
    // 在查询之前，需要将查询参数赋值给searchFormParams，包括分页参数
    CommonUtils.fillSortParams(searchFormParams, sortState.value);
    CommonUtils.fillPaginationParams(searchFormParams, pagination);
    // 将响应式对象通过toraw函数转化为普通对象
    const { data } = await getInspectionCheckListApi(toRaw(searchFormParams)).finally(
      () => {
        pageLoading.value = false;
      }
    );
    dataList.value = data.rows;
    pagination.total = data.total;
  }

  async function exportAllExcel() {
    if (sortState.value != null) {
      CommonUtils.fillSortParams(searchFormParams, sortState.value);
    }
    CommonUtils.fillPaginationParams(searchFormParams, pagination);
    CommonUtils.fillTimeRangeParams(searchFormParams, timeRange.value);

    exportInspectionCheckApi(toRaw(searchFormParams), "检查项数据.xlsx");
  }

  async function handleDelete(row) {
    await deleteInspectionCheckApi([row.inspectionCheckId]).then(() => {
      message(`您删除了编号为${row.inspectionCheckId}的这条检查项数据`, {
        type: "success"
      });
      // 刷新列表
      getInspectionCheckList();
    });
  }

  async function handleBulkDelete(tableRef) {
    if (multipleSelection.value.length === 0) {
      message("请选择需要删除的数据", { type: "warning" });
      return;
    }

    ElMessageBox.confirm(
      `确认要<strong>删除</strong>编号为<strong style='color:var(--el-color-primary)'>[ ${multipleSelection.value} ]</strong>的检查项数据吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        await deleteInspectionCheckApi(multipleSelection.value).then(() => {
          message(`您删除了编号为[ ${multipleSelection.value} ]的检查项数据`, {
            type: "success"
          });
          // 刷新列表
          getInspectionCheckList();
        });
      })
      .catch(() => {
        message("取消删除", {
          type: "info"
        });
        // 清空checkbox选择的数据
        tableRef.getTableRef().clearSelection();
      });
  }

  onMounted(async () => {
    await fetchDeptTree();
    getInspectionCheckList();
  });

  return {
    searchFormParams,
    pageLoading,
    columns,
    dataList,
    pagination,
    defaultSort,
    timeRange,
    multipleSelection,
    onSearch,
    onSortChanged,
    exportAllExcel,
    getInspectionCheckList,
    resetForm,
    handleDelete,
    handleBulkDelete,
    deptTree,
    inspectionResultOptions
  };
}
